// pages/countdown/countdown.js
Page({
  data: {
    clock: '00:00:00',
    isRunning: false,
    remainingTime: 0,
    selectedDuration: 1, // 默认选择 1 分钟
    durationOptions: [
      { id: 1, name: '1 分钟', value: 60 },
      { id: 5, name: '5 分钟', value: 300 },
      { id: 10, name: '10 分钟', value: 600 },
      { id: 30, name: '30 分钟', value: 1800 },
      { id: 60, name: '60 分钟', value: 3600 }
    ]
  },

  startStopCountdown() {
    if (this.data.isRunning) {
      clearInterval(this.data.timer);
      this.setData({
        isRunning: false
      });
    } else {
      const selectedDurationInSeconds = this.data.durationOptions.find(option => option.id === this.data.selectedDuration).value;
      this.setData({
        remainingTime: selectedDurationInSeconds,
        isRunning: true
      });
      this.data.timer = setInterval(() => {
        this.updateClock();
      }, 1000);
    }
  },

  resetCountdown() {
    clearInterval(this.data.timer);
    this.setData({
      clock: '00:00:00',
      remainingTime: 0,
      isRunning: false
    });
  },

  updateClock() {
    if (this.data.remainingTime > 0) {
      const hours = Math.floor(this.data.remainingTime / 3600);
      const minutes = Math.floor((this.data.remainingTime % 3600) / 60);
      const seconds = this.data.remainingTime % 60;
      const formattedClock = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      this.setData({
        clock: formattedClock,
        remainingTime: this.data.remainingTime - 1
      });
    } else {
      clearInterval(this.data.timer);
      this.setData({
        isRunning: false
      });
    }
  },

  selectDuration(e) {
    const selectedOption = this.data.durationOptions.find(option => option.id === e.currentTarget.dataset.id);
    const totalSeconds = selectedOption.value;
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const formattedDuration = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:00`;
    this.setData({
      selectedDuration: e.currentTarget.dataset.id,
      clock: formattedDuration
    });
  }
});